import { useState, useRef, useEffect } from 'react';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import { crud, updateRoles, updatePassword } from './api';
import type { TreeData } from './form';
import BasicForm, { UpdateRolesForm } from './form';
import BasicFormTable from '@/components/BasicFormTable';
import type { BasicModalFormRef } from '@/components/BasicModalForm';
import BasicModalForm from '@/components/BasicModalForm';
import { handleUpdate } from '@/utils/handler';
import PasswordForm from '@/components/UserForm/PasswordForm';
import { getTenantOptions } from '../Tenant/api';
import { getRoleOptions } from '../Role/api';
import { message } from 'antd';

export default () => {
  const tableRef = useRef<ActionType>();

  const roleRef = useRef<BasicModalFormRef>(null);
  const passwordRef = useRef<BasicModalFormRef>(null);
  const [currentRow, setCurrentRow] = useState<UserEntity>();
  const [roleTree, setRoleTree] = useState<TreeData[]>();

  const onReload = () => {
    tableRef?.current?.reload?.();
  };

  const initRoleTree = async () => {
    try {
      const tenantOptions = await getTenantOptions();
      const promises = tenantOptions.map((item) => getRoleOptions(item.value));
      const results = await Promise.all(promises);
      setRoleTree(
        tenantOptions.map((item, index) => ({
          key: item.value,
          title: item.label,
          checkable: false,
          selectable: false,
          pKey: '',
          pTitle: '',
          children: results[index].map((r) => ({
            key: r.value,
            title: r.label,
            checkable: true,
            selectable: false,
            isLeaf: true,
            pKey: tenantOptions[index].value,
            pTitle: tenantOptions[index].label,
          })),
        })),
      );
    } catch (error) {
      message.error('加载角色树出错');
    }
  };

  useEffect(() => {
    initRoleTree();
  }, []);

  const columns: ProColumns<UserEntity>[] = [
    {
      title: '账号',
      dataIndex: 'username',
    },
    {
      title: '姓名',
      dataIndex: 'name',
      render: (text, record) => `${record.first_name}${record.last_name}`,
    },
    {
      title: '邮箱',
      dataIndex: 'email',
    },
  ];

  return (
    <>
      <BasicFormTable<UserEntity>
        tableRef={tableRef}
        title={'用户'}
        columns={columns}
        search={false}
        crud={crud}
        addForm={<BasicForm isPersonal={false} isAdd={true} />}
        updateForm={<BasicForm isPersonal={false} isAdd={false} />}
        renderActions={(actions, record) =>
          [
            <a
              key="roles"
              onClick={async () => {
                setCurrentRow(record);
                roleRef.current?.open();
              }}
            >
              分配角色
            </a>,
            <a
              key="password"
              onClick={async () => {
                setCurrentRow(record);
                passwordRef.current?.open();
              }}
            >
              修改密码
            </a>,
          ].concat(actions)
        }
      />
      <BasicModalForm
        ref={roleRef}
        title={'分配角色'}
        onSubmit={(data) => {
          const { groups } = data;
          const newValue = { group_id: groups.map((item: UserGroupEntity) => item.id).join(',') };
          return handleUpdate({ ...newValue, id: currentRow?.id }, updateRoles);
        }}
        onReload={onReload}
        values={currentRow}
      >
        <UpdateRolesForm roleTree={roleTree} />
      </BasicModalForm>
      <BasicModalForm
        ref={passwordRef}
        title={'修改密码'}
        onSubmit={(data) => handleUpdate({ ...data, id: currentRow?.id }, updatePassword)}
        onReload={onReload}
        values={{ need_renew: false }}
      >
        <PasswordForm isPersonal={false} />
      </BasicModalForm>
    </>
  );
};
